import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'
import type { LoginParams, UserInfo } from '@/types/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const hasPermission = computed(() => (permission: string) => {
    return permissions.value.includes(permission) || permissions.value.includes('*')
  })

  // 初始化认证状态
  const initializeAuth = () => {
    const savedToken = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
    }
  }

  // 检查认证状态
  const checkAuthStatus = async () => {
    if (token.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        // 如果获取用户信息失败，清除token
        token.value = ''
        localStorage.removeItem('token')
        sessionStorage.removeItem('token')
      }
    }
  }

  // 登录
  const login = async (loginParams: LoginParams) => {
    const response = await loginApi(loginParams)
    const { token: newToken, user, permissions: userPermissions } = response.data
    
    token.value = newToken
    userInfo.value = user
    permissions.value = userPermissions
    
    // 存储token
    if (loginParams.rememberMe) {
      localStorage.setItem('token', newToken)
    } else {
      sessionStorage.setItem('token', newToken)
    }
    
    return response
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    const response = await getUserInfoApi()
    userInfo.value = response.data.user
    permissions.value = response.data.permissions
    return response
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 清除所有状态
      token.value = ''
      userInfo.value = null
      permissions.value = []
      
      // 清除存储
      localStorage.removeItem('token')
      sessionStorage.removeItem('token')
    }
  }

  return {
    token,
    userInfo,
    permissions,
    isAuthenticated,
    hasPermission,
    initializeAuth,
    checkAuthStatus,
    login,
    fetchUserInfo,
    logout
  }
})
